<template>
  <div class="PictureSet">
    <slot name="handle"></slot>

    <el-tabs
      v-model="activeName"
      type="card"
      :before-leave="beforeLeave"
      class="my-tab-pane card-side-line"
    >
      <div class="flex justify-between items-center h-[44px]">
        <div class="header-title">产品图片设置</div>
        <div class="flex">
          <el-button
            @click="copySKU"
            :disabled="permission_picture"
            v-if="handleType != 'view' && formData.goods_sku.length > 1"
          >
            <svg-icon icon-class="copy" class="mr-[2px]" />
            复制SKU图片</el-button
          >
        </div>
      </div>

      <el-tab-pane
        v-for="(item, index) in filtergallery(galleryList)"
        :key="item.custom_tag"
        :label="item.custom_tag"
        :name="item.custom_tag"
        class="relative"
      >
        <template #label>
          <span>{{ item.custom_tag }}</span>
          <svg-icon
            class="ml-2 inline-block"
            icon-class="Edit"
            @click="editEdit(item, index)"
            v-if="!disabled"
          ></svg-icon>
          <span
            v-if="item.language_id_text"
            class="font-[10px] absolute -left-[4px] -top-[4px] bg-[#FAAD14] text-[#fff] rounded-tl-[4px] rounded-br-[4px] h-[20px] leading-[20px] px-[5px] scale-75"
          >
            {{ item.language_id_text }}
          </span>
          <div
            class="absolute -right-[2px] -top-[2px]"
            @click.stop="removeTab(item.custom_tag)"
            v-if="!disabled"
          >
            <img class="w-[18px] h-[18px]" src="@/assets/images/closable.png" />
          </div>
        </template>
        <Module
          v-model="filtergallery(galleryList)[index].contents"
          :customTag="item.custom_tag"
          :currentIndex="props.currentIndex"
          :customIndex="index"
          :id="item.id"
        ></Module>
      </el-tab-pane>
      <el-tab-pane key="add" name="add" class="flex" v-if="!disabled">
        <template #label>
          <span class="flex items-centerc">
            <svg-icon icon-class="add" class="mt-3" />
          </span>
        </template>
      </el-tab-pane>
    </el-tabs>
  </div>
  <SelectTag ref="selectTagRef" @add="confirmAddTag" @edit="confirmEditTag"></SelectTag>
</template>

<script setup name="PictureSet">
import { nextTick, toRefs } from "vue";
import Module from "./components/Module.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import SelectTag from "@/components/Selects/SelectTag";

let options = reactive(inject("options"));
let formData = reactive(inject("form"));
let handleType = reactive(inject("handleType"));
const emits = defineEmits(["update:modelValue", "copySKUFun"]);
const copySKU = () => {
  emits("copySKUFun", "picture");
};
// 图片任务权限
const permission_picture = computed(() => {
  return (
    handleType.value == "edit" &&
    !(window.BTN_AUTH || []).includes("/goods/task/product/picture-info")
  );
});

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
  currentIndex: {
    type: Number,
  },
});

const disabled = computed(() => {
  return (
    handleType.value == "view" ||
    (handleType.value == "edit" &&
      !(window.BTN_AUTH || []).includes("/goods/task/product/picture-info"))
  );
});

const galleryList = computed({
  get: () => {
    if (props.modelValue.length) {
      activeName.value = props.modelValue[0].custom_tag;
    }
    return props.modelValue;
  },
  set: (val) => {
    emit("update:modelValue", val);
  },
});

const attr_img = computed(() => {
  return formData.value.goods_sku[props.currentIndex].attr_img;
});

provide("galleryList", galleryList);
provide("attr_img", attr_img);

const filtergallery = (list) => {
  return list.filter((i) => {
    if (!i.delete) {
      return i;
    }
  });
};

const data = reactive({
  custom_index: 0,
  activeName: "默认",
});

const { activeName, custom_index } = toRefs(data);

const selectTagRef = ref();
const addTab = () => {
  selectTagRef.value.open("add");
};
const removeTab = (targetName) => {
  if (filtergallery(galleryList.value).length <= 1) {
    return ElMessage.error("至少保留一个标签");
  }

  ElMessageBox.confirm("是否删除该标签及标签中图片？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
  })
    .then(async () => {
      galleryList.value.forEach((tab, index) => {
        if (tab.custom_tag == targetName) {
          if (handleType.value == "edit" && tab.id) {
            galleryList.value[index].delete = 1;
          } else {
            galleryList.value.splice(index, 1);
          }
          activeName.value = filtergallery(galleryList.value)[
            filtergallery(galleryList.value).length - 1
          ].custom_tag;
        }
      });
    })
    .catch(() => {});
};

const beforeLeave = (currentName) => {
  if (currentName == "add") {
    addTab();
    return false;
  }
};

const editEdit = (item, index) => {
  custom_index.value = index;
  selectTagRef.value.open("edit", {
    custom_tag: item.custom_tag,
    language_code: item.language_code,
    language_id: item.language_id,
    language_name: item.language_name,
  });
};

const init = () => {
  nextTick(() => {
    activeName.value = galleryList.value[0].custom_tag;
  });
};

// 新增标签回调
const confirmAddTag = (data) => {
  let image_types = [];
  let imageTypeText = options.value["gallery.GoodsSkuGalleryContents"]?.[0].imageTypeText;
  imageTypeText.forEach((item) => {
    image_types.push({
      label: item.label,
      image_type: item.value,
      showType: 0,
      values: [],
    });
  });

  console.log(data.custom_tag_list);
  data.custom_tag_list.forEach((item) => {
    const image_types = imageTypeText.map((item) => ({
      label: item.label,
      image_type: item.value,
      showType: 0,
      values: [],
    }));
    galleryList.value.push({
      custom_tag: item.custom_tag,
      language_code: item.language_code,
      language_id: item.language_id,
      language_id_text: item.language_id_text,
      spu: formData.value.spu,
      spu_category: formData.value.spu_category,
      spu_cn_title: formData.value.spu_cn_title,
      contents: image_types,
    });
  });
};

// 编辑标签回调
const confirmEditTag = (item) => {
  activeName.value = item.custom_tag;
  galleryList.value[custom_index.value].custom_tag = item.custom_tag;
  galleryList.value[custom_index.value].language_code = item.language_code;
  galleryList.value[custom_index.value].language_id = item.language_id;
  galleryList.value[custom_index.value].language_id_text = item.language_id_text;
};

const main_img = computed(() => {
  return formData.value.goods_sku[props.currentIndex].attr_img;
});
const validate = () => {
  let data = filtergallery(galleryList.value);
  const hasNonEmptyValues = data.some((item) =>
    item.contents.some((content) => content.values.length > 0)
  );
  if (hasNonEmptyValues) {
    return true;
  } else {
    ElMessage.warning("产品图片中至少需要一张图片作为主图!");
    return false;
  }
};
defineExpose({ init, validate });
</script>
<style lang="scss" scoped>
.PictureSet {
  flex: 1;
  position: relative;
}

.Picture-card {
  margin: 8px;

  :deep(.el-card__header) {
    border-bottom: 1px solid #ccc;
  }
}

:deep(.el-tabs__nav) {
  display: flex;
}

:deep(.el-card__body) {
  display: flex;
  flex-direction: column;
}

.PictureSet {
  :deep(.el-card__body) {
    width: 100%;
    display: flex;
    justify-content: flex-start;

    :deep(.header-title) {
      width: 120px !important;
    }
  }

  :deep(.el-tabs__nav-scroll) {
    :deep(.el-tabs__nav) {
      margin-left: 100px;
      width: calc(100% - 100px);
      display: flex;
      justify-content: flex-end;
    }
  }
}
@import "../../index.scss";
</style>
